package com.example.interceptors;


import cn.hutool.core.util.ObjectUtil;
import com.example.common.Constants;
import com.example.common.enums.ResultCodeEnum;
import com.example.entity.Account;
import com.example.exception.CustomException;
import com.example.service.LogoutService;
import com.example.utils.JwtUtil;
import com.example.utils.RedisUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);


    @Autowired
    private RedisUtils redisUtils;  // 使用 RedisUtils 工具类


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 从请求头中获取token
        String token = request.getHeader(Constants.TOKEN);

        if (ObjectUtil.isEmpty(token)) {
            // 如果没拿到，尝试从参数里拿
            token = request.getParameter(Constants.TOKEN);
        }

        log.info("JwtInterceptor.preHandle: token = " + token);


        // 如果token为空，直接拒绝请求
        if (token == null || token.isEmpty()) {
            throw new CustomException(ResultCodeEnum.TOKEN_NULL);
        }

        try {
            // 解析token，获取其中的claims
            Map<String, Object> claims = JwtUtil.parseToken(token);

            // 从claims中获取用户名
            String username = (String) claims.get("username");

            // 从Redis中获取对应的token，键为 "TOKEN_用户名"
            String redisKey = "TOKEN_" + username;
            String redisToken = (String) redisUtils.get(redisKey);  // 使用RedisUtils来获取token

            // 如果Redis中没有token，说明token已过期或未存储
            if (redisToken == null) {
                throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
            }

            // 校验Redis中的token与传入的token是否一致
            if (!redisToken.equals(token)) {
                // 清除Redis中该用户的旧token
                redisUtils.remove(redisKey);

                throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
            }
            // Token有效，放行
            return true;
        } catch (Exception e) {
            // 如果解析失败，或Redis中的token不匹配，拒绝请求
            throw  new CustomException(ResultCodeEnum.TOKEN_INVALID_ERROR);
        }
    }

}
